/**
 * Created by zhangxiaoyu on 16/12/08.
 */
angular.module('hyt.outerCtrl',[])

  .controller('transferCtrl',function($scope,$filter,$ionicModal,TransferList,Storage,$state){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    $scope.transferSearch={
      parameter:{
        TRANSFER_NO:'',
        TRANSFER_DATE:'',
        TRANSFER_DATE_TO:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    TransferList.getTransferData($scope.transferSearch);
    $scope.$on('TransferList.Updated', function() {
      $scope.transferData=TransferList.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      TransferList.getTransferData($scope.transferSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      TransferList.getMoreTransferData($scope.transferSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return TransferList.hasNextPage();
    };
    var t = new Date();
    var iToDay=t.getDate();
    var iToMon=t.getMonth();
    var iToYear=t.getFullYear();
    var iTDate=new Date(iToYear,iToMon,(iToDay-30));
    $scope.startDate=$filter('date')(iTDate,'yyyy-MM-dd');
    $scope.showStartDate = function() { //选择日期
      var optionsStart = {
        date: iTDate,
        mode: 'date',
        maxDate: new Date($scope.endDate) - 10000
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            iTDate=d;
            $scope.startDate = $filter('date')(iTDate,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.endDate=$filter('date')(new Date(),'yyyy-MM-dd');
    $scope.showEndDate = function(){
      console.log('EndDate');
      var optionsEnd = {
        date : new Date(),
        mode : 'date',
        minDate: new Date($scope.startDate) - 10000
      };
      datePicker.show(optionsEnd,function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            endTime=d;
            $scope.endDate = $filter('date')(endTime,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.searchTransfer=function(){
      $scope.transferSearch.parameter.TRANSFER_DATE=$scope.startDate;
      $scope.transferSearch.parameter.TRANSFER_DATE_TO=$scope.endDate;
      TransferList.getTransferData($scope.transferSearch);
      $scope.modal.hide();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/outer/searchTransferList.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.goTransDetail=function (id,data) {
      Storage.set('transDetail',data);
      $state.go('transDetail',{id:id});
    }
  })
  .controller('transDetailCtrl',function($scope,$filter,$ionicModal,$stateParams,Storage,TransferDetail){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    console.log(Storage.get('transDetail'));
    $scope.transDetail=Storage.get('transDetail');
    switch ($scope.transDetail.TRANSFER_STATUS){
      case '0' :
        $scope.transferStatus = '已中转';
        break;
      case '1' :
        $scope.transferStatus = '已受理';
        break;
      case '2' :
        $scope.transferStatus = '已拒绝';
        break;
      case '3' :
        $scope.transferStatus = '已承运';
        break;
      case '4' :
        $scope.transferStatus = '已作废';
        break;
      default :
        break;
    }
    $scope.transferDetailSearch={
      transferId:$stateParams.id,
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    TransferDetail.getTransferDetail($scope.transferDetailSearch);
    $scope.$on('TransferDetail.Updated', function() {
      $scope.transferDetailWaybill=TransferDetail.getResult();
      $scope.showloading=false;
    });
    //上拉加载更多
    $scope.loadMore=function(){
      TransferDetail.getMoreTransferDetail($scope.transferDetailSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return TransferDetail.hasNextPage();
    };
  })
  .controller('addGoodsCtrl',function($scope,$filter,$ionicModal,Storage,WayBillsToTrans,$state,$ionicLoading,$timeout){
    $scope.showloading=true;
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    $scope.wbToTransSearch={
      parameter:{
        WAYBILL_NO:'',
        DESTINATION_STATION:'',
        WAYBILL_DATE:'',
        WAYBILL_DATE_TO:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    $scope.deptName=userMsg.rows.deptName;
    WayBillsToTrans.getWbToTransData($scope.wbToTransSearch);
    $scope.$on('WbToTrans.Updated', function() {
      $scope.wbToTransData=WayBillsToTrans.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      WayBillsToTrans.getWbToTransData($scope.wbToTransSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      WayBillsToTrans.getMoreWbToTransData($scope.wbToTransSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return WayBillsToTrans.hasNextPage();
    };
    $scope.chBox=[];
    $scope.transferFee=[];
    var wayBillMap=[];
    $scope.wbChecked=function(index,id){
      $timeout(function(){
        $('#transferFee'+id).focus();
      },500);
      if($scope.chBox[index]==true){
        $('#transferFee'+id).css('display','flex');
        wayBillMap.push({ID:id,TRANSFER_CHARGE:$scope.transferFee[index]});
      }else {
        $('#transferFee'+id).hide();
        $.each(wayBillMap,function(i,item){
          $timeout(function(){
            if(item.ID==id){
              wayBillMap.splice(i,1);
            }
          },160);
        });
      }
    };
    $scope.transferOnblur=function(id,index){
      $.each(wayBillMap,function(i,item){
        if(item.ID==id){
          if (wayBillMap.length==1){
            wayBillMap[i].TRANSFER_CHARGE=$scope.transferFee[i+index];
          }else {
            wayBillMap[i].TRANSFER_CHARGE=$scope.transferFee[index];
          }
        }
      });
    };
    var t = new Date();
    var iToDay=t.getDate();
    var iToMon=t.getMonth();
    var iToYear=t.getFullYear();
    var iTDate=new Date(iToYear,iToMon,(iToDay-30));
    $scope.startDate=$filter('date')(iTDate,'yyyy-MM-dd');
    $scope.showStartDate = function() { //选择日期
      var optionsStart = {
        date: iTDate,
        mode: 'date',
        maxDate: new Date($scope.endDate) - 10000
      };
      datePicker.show(optionsStart, function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            iTDate=d;
            $scope.startDate = $filter('date')(iTDate,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.endDate=$filter('date')(new Date(),'yyyy-MM-dd');
    $scope.showEndDate = function(){
      console.log('EndDate');
      var optionsEnd = {
        date : new Date(),
        mode : 'date',
        minDate: new Date($scope.startDate) - 10000
      };
      datePicker.show(optionsEnd,function(d) {
        if (!isNaN(d.getTime())) {  // valid date
          $scope.$apply(function () {
            endTime=d;
            $scope.endDate = $filter('date')(endTime,'yyyy-MM-dd');
          });
        }
      });
    };
    $scope.searchWaybill=function(){
      $scope.wbToTransSearch.parameter.WAYBILL_DATE=$scope.startDate;
      $scope.wbToTransSearch.parameter.WAYBILL_DATE_TO=$scope.endDate;
      WayBillsToTrans.getWbToTransData($scope.wbToTransSearch);
      $scope.modal.hide();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/outer/searchGoods.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.confirmGoods=function(){
      console.log(wayBillMap);
      var isGoPage=true;
      var transferFeeTotal=0;
      if (wayBillMap.length==0){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择需中转的货物",
          duration: 1500
        });
      }else {
        $.each(wayBillMap,function(i,item){
          $timeout(function(){
            transferFeeTotal=transferFeeTotal+parseFloat(item.TRANSFER_CHARGE);
            if(item.TRANSFER_CHARGE==undefined||item.TRANSFER_CHARGE==''){
              isGoPage=false;
              $ionicLoading.show({
                noBackdrop: true,
                template: "请输入中转费",
                duration: 1500
              });
            }
            if (isGoPage==true&&i+1==wayBillMap.length){
              $state.go('fillInCompany',{transferFeeTotal:transferFeeTotal.toFixed(2)});
              Storage.set('wayBillMap',wayBillMap);
            }
          },160);
        });
      }
    }
  })
  .controller('FillInCompanyCtrl',function($scope,$state,$filter,$ionicModal,$stateParams,CooperationCompany,Storage,PaymentMethod,CooperationSite,SaveTransfer,$ionicLoading,$timeout){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    var wayBillMap=Storage.get('wayBillMap');
    var searchCompany={
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    //var searchSite={
    //  ID:'',
    //  userMsg:{
    //    username:loginMsg.username,
    //    password:loginMsg.password,
    //    uuid:loginMsg.uuid
    //  }
    //};
    $scope.transferFeeTotal=$stateParams.transferFeeTotal;
    $scope.transferCompanyMsg={
      wayBillMap:wayBillMap,
      transferMap:{
        ID:'',
        belongId:userMsg.rows.baseDeptId,
        transferCompanyId:'',
        company_phone:'',
        transferDate:$filter('date')(new Date(),'yyyy-MM-dd'),
        pay_type:'',
        userId:userMsg.rows.id,
        remark:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    CooperationCompany.getCompany(JSON.stringify(searchCompany));
    $scope.$on('Company.Updated', function() {
      var result=CooperationCompany.getResult();
      $scope.cptCompany=result.rows;
    });
    //$("#cptCompany").change(function(e) {
    //  searchSite.ID=$("#cptCompany").val();
    //  CooperationSite.getSite(JSON.stringify(searchSite));
    //  $scope.$on('Site.Updated', function() {
    //    var result=CooperationSite.getResult();
    //    $scope.cptSite=result.rows;
    //  });
    //});
    //付款方式
    var paymentMethod={
      type:'payment_method',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    PaymentMethod.getPaymentMethod(JSON.stringify(paymentMethod));
    $scope.$on('PaymentMethod.Updated', function() {
      var result=PaymentMethod.getResult();
      if (result.success==true){
        $scope.paymentMethods=result.rows;
      }
    });
    $scope.showDate = function() { //选择日期
        var optionsStart = {
            date:new Date(),
            mode: 'date'
        };
        datePicker.show(optionsStart, function(d) {
            if (!isNaN(d.getTime())) {  // valid date
                $scope.$apply(function () {
                    $scope.transferCompanyMsg.transferMap.transferDate = $filter('date')(d,'yyyy-MM-dd');
                });
            }
        });
    };
    $("#cptCompany").change(function(e) {
        $.each($scope.cptCompany,function(i,item){
          $timeout(function(){
            if (item.DEPT_ID==$("#cptCompany").val()){
              $scope.transferCompanyMsg.transferMap.company_phone=$scope.cptCompany[i].DEPT_PHONE;
            }
          },160);
        });
    });
    $scope.saveTransferBill=function(){
      $scope.transferCompanyMsg.transferMap.transferCompanyId=$('#cptCompany').val();
      $scope.transferCompanyMsg.transferMap.pay_type=$('#paymentMethod').val();
      console.log($scope.transferCompanyMsg);
      if ($scope.transferCompanyMsg.transferMap.transferCompanyId==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: "请选择中转公司",
          duration: 1500
        });
      }else {
        SaveTransfer.getSaveTransfer(JSON.stringify($scope.transferCompanyMsg));
      }
      $scope.$on('SaveTransfer.Updated', function() {
        var result=SaveTransfer.getResult();
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: "保存成功",
            duration: 1500
          });
          $state.go('tab.workbench');
        }
      });
    };
    $scope.goFillInDriver=function(){
      $state.go('fillInDriver',{transferFeeTotal:$scope.transferFeeTotal});
    }
  })
  .controller('FillInDriverCtrl',function($scope,$state,$filter,$ionicModal,$stateParams,Storage,PaymentMethod,SaveTransfer,$ionicLoading,Vehicles){
    var loginMsg=Storage.get('user');
    var userMsg=Storage.get('loginResult');
    var wayBillMap=Storage.get('wayBillMap');
    //车牌号
    $scope.showloading=true;
    $scope.vehiclesSearch={
      VEHICLE_NO:'',
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    Vehicles.getVehicles($scope.vehiclesSearch);
    $scope.$on('Vehicles.Updated', function() {
      $scope.vehiclesData=Vehicles.getResult();
      $scope.showloading=false;
    });
    //下拉刷新
    $scope.doRefresh=function(){
      Vehicles.getVehicles($scope.vehiclesSearch);
      $scope.$broadcast('scroll.refreshComplete');
    };
    //上拉加载更多
    $scope.loadMore=function(){
      Vehicles.getMoreVehicles($scope.vehiclesSearch);
      $scope.$broadcast('scroll.infiniteScrollComplete');
    };
    //下一页
    $scope.hasNextPage = function() {
      return Vehicles.hasNextPage();
    };
    $ionicModal.fromTemplateUrl('templates/tab-workbench/outer/vehicles.html', {
      scope: $scope
    }).then(function(modal) {
      $scope.modal = modal;
    });
    $scope.chooseVehicles=function(VEHICLE_NO,id){
      $scope.transferDriverMsg.transferMap.plateNumber=VEHICLE_NO;
      $scope.transferDriverMsg.transferMap.VEHICLE_NO=id;
      $scope.modal.hide();
    };
    $scope.transferFeeTotal=$stateParams.transferFeeTotal;
    $scope.transferDriverMsg={
      wayBillMap:wayBillMap,
      transferMap:{
        ID:'',
        belongId:userMsg.rows.baseDeptId,
        transferCompanyId:'',
        driverName:'',
        driverMobile:'',
        plateNumber:'',
        VEHICLE_NO:'',
        pay_type:'',
        userName:userMsg.rows.username,
        remark:''
      },
      userMsg:{
        username:loginMsg.username,
        password:loginMsg.password,
        uuid:loginMsg.uuid
      }
    };
    //付款方式
    var paymentMethod={
      type:'payment_method',
      username:loginMsg.username,
      password:loginMsg.password,
      uuid:loginMsg.uuid
    };
    PaymentMethod.getPaymentMethod(JSON.stringify(paymentMethod));
    $scope.$on('PaymentMethod.Updated', function() {
      var result=PaymentMethod.getResult();
      if (result.success==true){
        $scope.paymentMethods=result.rows;
      }
    });
    $scope.saveTransferBill=function(){
      $scope.transferDriverMsg.transferMap.pay_type=$('#paymentMethod').val();
      console.log($scope.transferDriverMsg);
      SaveTransfer.getSaveTransfer(JSON.stringify($scope.transferDriverMsg));
      $scope.$on('SaveTransfer.Updated', function() {
        var result=SaveTransfer.getResult();
        if (result.success==true){
          $ionicLoading.show({
            noBackdrop: true,
            template: "保存成功",
            duration: 1500
          });
          $state.go('tab.workbench');
        }
      });
    };
  });
